<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>优先级队列priorityQueue</title>
</head>
<body>
</body>
</html>
<script>
    // 优先级队列， （element, priority）
    function PriorityQueue() {
        this.list = [];

        // 优先级队列元素,element: 元素  priority: 优先级
        // 优先级越小的元素排到队列前面
        function Priority(element, priority) {
            this.element = element;
            this.priority = priority;
        }

        PriorityQueue.prototype.insert = function(element, priority) {
            // 队列为空时，直接插入
            if(this.list.length === 0){
                this.list.push(element);
            }else{
                // 队列不为空，需要跟队列元素的优先级进行比较
                for(var i = 0; i < this.list.length; i++) {
                    var added = false;
                    if(element.priority < this.list[i].priority){
                        this.list.splice(i, 0, element);
                        added = true;
                        break;
                    }
                    if(!added){
                        this.list.push(element);
                    }
                }
            }
        }
    }
</script>